package com.vanchu.dropdownview.component;

import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.vanchu.dropdownview.Dp2Px;

/**
 * Created by grant on 16-12-30.
 */
public class DropDownView {

    private static final String TAG = DropDownView.class.getSimpleName();

    private final View anchorView;

    private final PopupWindow popupWindow;

    public DropDownView(View anchorView, View contentView) {
        this.anchorView = anchorView;
        this.popupWindow = new PopupWindow(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        if (contentView != null) {
            this.setWindowContentView(contentView);
        }
    }

    public DropDownView(View anchorView) {
        this(anchorView, null);
    }

    public void setWindowContentView(View contentView) {
        this.popupWindow.setContentView(contentView);
        setOutSideTouchAble();
    }

    public void show() {
        this.popupWindow.showAsDropDown(anchorView);
    }

    public void show(int xOff, int yOff) {
        xOff = (int) Dp2Px.dp2px(this.popupWindow.getContentView().getContext(), xOff);
        int popupWindowWidth = getPopupWindowWidth();
        int anchorViewWidth = anchorView.getWidth();
        int delta = popupWindowWidth - anchorViewWidth;
        Log.i(TAG, "show: delta is " + delta);
        xOff = xOff - delta;
        this.popupWindow.showAsDropDown(anchorView, xOff, yOff);
    }

    public void close() {
        if (this.popupWindow == null) {
            return;
        }
        this.popupWindow.dismiss();
    }

    private int getPopupWindowWidth() {
        return getViewMeasuredWidth(this.popupWindow.getContentView());
    }

    private void setOutSideTouchAble() {
        this.popupWindow.setFocusable(true);
        this.popupWindow.setOutsideTouchable(true);
        this.popupWindow.setBackgroundDrawable(
                new ColorDrawable(this.anchorView.getResources().getColor(android.R.color.transparent))
        );
    }

    private static int getViewMeasuredWidth(View view) {
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
        view.measure(width, expandSpec);
        return view.getMeasuredWidth();
    }

}